var $ = getApp(), methods = require("../methods.js");
Page(Object.assign({},methods,{
	data: {
		st: 0,
		datalist: [],
		pagenum: 1,
		title: '文章列表',
	},
	_onLoad: function () {
		var that = this;
		if (that.options.st) {
			that.setData({ st: that.options.st })
		}
		this.setData({ pagenum:1,st:that.data.st,datalist:[],$nomoreData:false})
		that.getDataList();
	},
	changetab: function (e) {
		var st = e.currentTarget.dataset.st
		this.setData({ pagenum:1,st: st,datalist:[],$nomoreData:false})
		wx.pageScrollTo({
			scrollTop:0,duration:0
		})
		this.getDataList()
	},
	getDataList: function(){
		var that = this
		var pagenum = that.data.pagenum
		var st = that.data.st
		var bid = (that.options && (that.options.bid || that.options.bid==='0') ? that.options.bid:'');
		$.post('coupon/couponlist', {st:st,pagenum:pagenum,bid:bid}, function (res) {
			var data = res.datalist
			if(pagenum == 1){
				that.setData({ datalist: data });
				if (data.length == 0){
					$.showEmpty('暂无可领'+(that.data.textset['优惠券'] || '优惠券'),'/images/empty2.png');
				}
			}else{
				if (data.length == 0){
					that.setData({$nomoreData:true});
				}else{
					var datalist = that.data.datalist
					var newdata = datalist.concat(data)
					that.setData({ datalist: newdata });
				}
			}
		});
	},
	onReachBottom: function () {
		if (!this.data.$dataEmpty.visible && !this.data.$nomoreData){
			this.setData({ pagenum: this.data.pagenum+1 })
			this.getDataList();
		}
	},
	getcoupon:function(e){
		if($.mid==0){
			this.setData({needAuth:1,authCanClose:true});
		}else{
			var that = this
		
			var datalist = that.data.datalist
			var id = e.currentTarget.dataset.id;
			var score = parseInt(e.currentTarget.dataset.score);
			var price = e.currentTarget.dataset.price;
			if(price > 0){
				$.goto('/pages/wxpay/buycoupon?id='+id);
				return ;
			}
			var key = e.currentTarget.dataset.key;
			//if(datalist[key]['haveget'] == 1) return;
			if(score > 0){
				$.confirm('确定要消耗'+score+''+(that.data.textset['积分'] || '积分')+'兑换吗?',function(){
					$.post('coupon/getcoupon',{id:id},function(data){
						if(data.status==0){
							$.error(data.msg);
						}else{
							$.success(data.msg);
							datalist[key]['haveget'] = data.haveget;
							that.setData({datalist : datalist});
						}
					},'兑换中');
				})
			}else{
				$.post('coupon/getcoupon',{id:id},function(data){
					if(data.status==0){
						$.error(data.msg);
					}else{
						$.success(data.msg);
						datalist[key]['haveget'] = data.haveget;
						that.setData({datalist : datalist});
					}
				},'领取中');
			}
		}
	}
}))